#!/bin/sh
function wait_mysql(){
    while [ true ]
    do
        sleep 1
        port=`netstat -lnt | grep 3306 | wc -l`  
        pid=`ps -ef | grep mysql | grep -v grep | wc -l`
        if [ $port -eq 1 ] && [ $pid -eq 1 ]; then
            break
        fi
    done
}

if [ "$1" = "sh" ]; then
    exec "sh"
else
    if [ -f /etc/lnmp.sit ]; then
        echo "[i] LNMP start..."
        exec /usr/bin/mysqld --user=root --console  &
        wait_mysql
    else
        echo "[i] Install LNMP... "
        MIRRORS_USTC=${MIRRORS_USTC:-""}
        if [ "$MIRRORS_USTC" != "" ]; then
            sed -i 's/dl-cdn.alpinelinux.org/mirrors.ustc.edu.cn/g' /etc/apk/repositories
            sed -i 's/#http/http/g' /etc/apk/repositories
        fi
        apk update && apk upgrade

        apk --no-cache add tzdata
        ln -sf /usr/share/zoneinfo/Asia/Shanghai /etc/localtime
        echo "Asia/Shanghai" > /etc/timezone
        apk --no-cache add php php-common php-gd php-xml php-simplexml php-mbstring php-fileinfo php-opcache php-fpm php-pdo php-pdo_mysql php-mysqli php-ctype php-session
        apk --no-cache add mysql mysql-client

        cd /app
        mv /etc/nginx/conf.d/default.conf /etc/nginx/conf.d/default.bak

        mysql_install_db --user=root > /dev/null
        MYSQL_ROOT_PASSWORD=${MYSQL_ROOT_PASSWORD:-""}
        if [ "$MYSQL_ROOT_PASSWORD" = "" ]; then
            MYSQL_ROOT_PASSWORD=111111
            echo "[i] MySQL root Password: $MYSQL_ROOT_PASSWORD"
        fi

        tfile=`mktemp`
        if [ ! -f "$tfile" ]; then
            return 1
        fi
        cat << EOF > $tfile
USE mysql;
FLUSH PRIVILEGES;
GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY "$MYSQL_ROOT_PASSWORD" WITH GRANT OPTION;
GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' WITH GRANT OPTION;
ALTER USER 'root'@'localhost' IDENTIFIED BY 'root2240881';
EOF

        MYSQL_DATABASE=${MYSQL_DATABASE:-""}
        if [ "$MYSQL_DATABASE" != "" ]; then
            echo "[i] Creating database: $MYSQL_DATABASE"
            echo "CREATE DATABASE IF NOT EXISTS \`$MYSQL_DATABASE\` CHARACTER SET utf8mb4 COLLATE utf8mb4_general_ci;" >> $tfile
        fi
    
        /usr/bin/mysqld --user=root --bootstrap --verbose=0 < $tfile
        rm -f $tfile
        exec /usr/bin/mysqld --user=root --console  &

        sed -i "s/post_max_size = 8M/post_max_size = 128M/g" /etc/php83/php.ini
        sed -i "s/upload_max_filesize = 2M/upload_max_filesize = 128M/g" /etc/php83/php.ini        

        wait_mysql
        echo "LNMP installation complete." > /etc/lnmp.sit
    fi
    php-fpm83 
    nginx -g "daemon off;"
fi
